package com.parkcar;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import HttpUtils.HttpInfoRequest;
import HttpUtils.HttpQniuRequest;
import Modle.InfoBean;
import util.BaseActivity;
import util.BaseTools;
import util.BaseUtil;
import util.Constrants;
import util.FileUtil;
import util.PhotoUtil;

/**
 * Created by Administrator on 2016/1/14.
 */
public class InfoActivity extends BaseActivity {
    private ImageView header_iv;
    private TextView name_tv, phone_tv, sex_tv;
    private PopupWindow changePop;
    private String headerUrl = "";
    private Bitmap logobitmap;
    private File mlogoFile;
    private InfoBean mInfo;
    private HttpInfoRequest infoRequest;
    private HttpInfoRequest loginOutRequest;
    private HttpQniuRequest qniuRequest;

    @Override
    protected void setUpui(Bundle arg0) {
        setContentView(R.layout.activity_info);
        setTitle("个人信息");
        sex_tv = (TextView) findViewById(R.id.sex_tv);
        phone_tv = (TextView) findViewById(R.id.phone_tv);
        name_tv = (TextView) findViewById(R.id.name_tv);
        header_iv = (ImageView) findViewById(R.id.header_iv);
        mInfo = Constrants.mInfo;
        if (BaseTools.isValueEmpty(BaseUtil.getQNToken(this))) {
            getToken();
        }
        initData();
    }

    void initData() {
        if (mInfo != null) {
            if (!BaseTools.isValueEmpty(mInfo.getHeadShotUrl())) {
                ImageLoader.getInstance().displayImage(mInfo.getHeadShotUrl(), header_iv);
            }
            name_tv.setText(BaseTools.isValueEmpty(mInfo.getNickName()) ? "点击设置" : mInfo.getNickName());
            if (mInfo.getSex() == 0) {
                sex_tv.setText("男");
            } else if(mInfo.getSex()==1){
                sex_tv.setText("女");
            }else{
                sex_tv.setText("");
            }
            phone_tv.setText(mInfo.getMobile());
        }
    }

    @Override
    protected void updateUI(boolean isLogin) {
        if (!isLogin) {
            finish();
        }
    }

    /**
     * 修改头像
     *
     * @param view
     */
    public void changeHeader(View view) {
        if (changePop == null) {
            initPop();
        }
        changePop.showAtLocation(contentLayout, Gravity.BOTTOM, 0, 0);
    }

    private void initPop() {
        View views = getLayoutInflater().inflate(R.layout.pop_change_image, null);
        changePop = new PopupWindow(views, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        changePop.setFocusable(true);
        changePop.setBackgroundDrawable(new ColorDrawable(0x90000000));
        TextView first_tv = (TextView) views.findViewById(R.id.first_tv);
        TextView sec_tv = (TextView) views.findViewById(R.id.sec_tv);
        TextView cancle_tv = (TextView) views.findViewById(R.id.cancle_tv);
        first_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File file = PhotoUtil.getImageFile(InfoActivity.this, "header.png");
                headerUrl = file.getAbsolutePath();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                intent.putExtra("return-data", true);
                intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
                intent.putExtra("noFaceDetection", true); // no face detection
                startActivityForResult(intent, 0);

            }
        });
        sec_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                    /* 开启Pictures画面Type设定为image */
                intent.setType("image/*");
                    /* 使用Intent.ACTION_GET_CONTENT这个Action */
                intent.setAction(Intent.ACTION_GET_CONTENT);
                    /* 取得相片后返回本画面 */
                intent.putExtra("return-data", true);
                intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
                startActivityForResult(intent, 1);
            }
        });
        cancle_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changePop.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            try {
                if (requestCode == 1) {
                    headerUrl = PhotoUtil.GetPhotoPath(InfoActivity.this, data);
                }
                logobitmap = PhotoUtil.CompresPhoto(headerUrl, 360, 360);
				/* 将Bitmap设定到ImageView */
                mlogoFile = FileUtil.saveBitmap(InfoActivity.this, logobitmap, "header.png");
                if (mlogoFile != null) {
                    upHeaderImg();

                }
            } catch (Exception e) {
                Log.e("Exception", e.getMessage(), e);
            }
        } else if (requestCode == Constrants.CHANGE_NAME && requestCode == Constrants.CHANGE_NAME) {
            mInfo = Constrants.mInfo;
            name_tv.setText(mInfo.getNickName());
        } else if (requestCode == Constrants.CHANGE_SEX && requestCode == Constrants.CHANGE_SEX) {
            mInfo = Constrants.mInfo;
            if (mInfo.getSex() == 0) {
                sex_tv.setText("男");
            } else if (mInfo.getSex() == 1) {
                sex_tv.setText("女");
            } else {
                sex_tv.setText("");
            }
        }
    }

    private void upHeaderImg() {
        if (!BaseTools.isConnection(this)) {
            toast("亲,您的网络开小差了，请检查网络后重试");
            return;
        }
        UploadManager uploadManager = new UploadManager();
        uploadManager.put(mlogoFile, null, BaseUtil.getQNToken(this),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //  res 包含hash、key等信息，具体字段取决于上传策略的设置。
                        try {

                            String url = (String) res.get("key");
                            infoRequest = new HttpInfoRequest(InfoActivity.this, 3);
                            infoRequest.setmIHttpClinetListener(InfoActivity.this);
                            infoRequest.changeInfo("", -1, url);
                            infoRequest.doRequest();
                            changePop.dismiss();
                            Log.e("key", url);
                        } catch (Exception e) {
                            toast("上传失败");
                        }
                    }

                }, null);
    }

    public void changeBaseInfo(View view) {
        showActivity(NameChangeActivity.class, null, Constrants.CHANGE_NAME);
    }

    @Override
    public void httpSuccessListener(Bundle successMsg) {
        super.httpSuccessListener(successMsg);
        if (mBaseResult == null) {
            toast("您的网络开小菜了，请检查网络后重试");
            return;
        }
        if (loginOutRequest != null && action.equalsIgnoreCase(loginOutRequest.getAction())) {
            if (mBaseResult.getStatus().getRetCode() == 0) {
                BaseUtil.setToken(this,"");
                toast("退出成功");
                Constrants.mInfo=new InfoBean();
                Intent mIntent = new Intent();
                mIntent.setAction("login");
                mIntent.putExtra("login", false);
                sendBroadcast(mIntent);
                finish();
            } else {
                toast(mBaseResult.getStatus().getMsg());
            }
        } else if (infoRequest != null && action.equalsIgnoreCase(infoRequest.getAction())) {
            if (mBaseResult.getStatus().getRetCode() == 0) {
                toast("头像修改成功");
                mInfo = mBaseResult.toObject(InfoBean.class);
                if (mInfo != null) {
                    Constrants.mInfo = mInfo;
                }
                header_iv.setImageBitmap(logobitmap);
            } else {
                toast(mBaseResult.getStatus().getMsg());
            }
            setResult(Constrants.CHANGE_HEAD);
        } else if (qniuRequest != null && action.equalsIgnoreCase(qniuRequest.getAction())) {
            if (mBaseResult != null && mBaseResult.getStatus().getRetCode() == 0) {
                String token = mBaseResult.getData();
                BaseUtil.setQNToken(this, token);
            }
        }
    }

    public void changeSex(View view) {
        showActivity(SexChangeActivity.class, null, Constrants.CHANGE_SEX);
    }

    /**
     * 退出登录
     *
     * @param view
     */
    public void loginOut(View view) {
        loginOutRequest = new HttpInfoRequest(this, 4);
        loginOutRequest.setmIHttpClinetListener(this);
        loginOutRequest.doRequest();

    }

    private void getToken() {
        qniuRequest = new HttpQniuRequest(this);
        qniuRequest.setmIHttpClinetListener(this);
        qniuRequest.doRequest();
    }
}
